package com.apimarket.config;

import com.alibaba.druid.pool.DruidDataSource;

import lombok.Data;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jta.atomikos.AtomikosDataSourceBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;
import java.io.IOException;
import java.util.Properties;

/**
 * @Description:
 * @Author ZXR
 * @Date 2021/7/9 14:20
 * @Version 1.0
 */

@Data
@Configuration
@MapperScan(basePackages = SlaveDataBaseConfig.PACKAGE,sqlSessionFactoryRef = "slaveSqlSessionFactory")
public class SlaveDataBaseConfig {
    /**
     * dao层的包路径
     */
    static final String PACKAGE="com.apimarket.slaveDao";
    /**
     * mapper文件的相对路径
     */
    private static final String MAPPER_LOCATION="classpath*:mapper/slave/*.xml";



    //创建从数据源
    @Bean(name="slaveDataSource")
    @ConfigurationProperties(prefix="spring.datasource.druid.slave")
    public DataSource slaveDataSource(){
        return new DruidDataSource();
    }
    //创建从数据源的事务管理
    @Bean(name = "slaveTransactionManager")
    public DataSourceTransactionManager backTransactionManager(@Qualifier("slaveDataSource")DataSource dataSource){
        return new DataSourceTransactionManager(dataSource);
    }
    //创建Mybatis连接会话工厂实例
    @Bean(name="slaveSqlSessionFactory")
    public SqlSessionFactory slaveSqlSessionFactory(@Qualifier("slaveDataSource")DataSource dataSource) throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);
        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources(SlaveDataBaseConfig.MAPPER_LOCATION));

        return sessionFactory.getObject();
    }
}
